/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.lib.client.service;

import org.lucava.lib.shared.service.RemoteResponse;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.ArrayList;
import java.util.List;
import org.lucava.boatskeeper.client.event.ErrorEvent;

/**
 *
 * @author glenn
 */
public class SecureServiceProxy {

    private final EventBus eventBus;

    public SecureServiceProxy(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    public EventBus getEventBus() {
        return eventBus;
    }

    protected AsyncCallback buildCallBack(final AsyncAction asyncCallback) {
        return new AsyncCallback<RemoteResponse<Object>>() {
            @Override
            public void onSuccess(RemoteResponse<Object> result) {
                if (!result.isSuccess()) {
                    getEventBus().fireEvent(new ErrorEvent(result.getMessages()));
                } else {
                    asyncCallback.execute(result.getValue());
                }


            }

            @Override
            public void onFailure(Throwable caught) {
                List<String> messages = new ArrayList<String>();
                messages.add(caught.getMessage());
                getEventBus().fireEvent(new ErrorEvent(messages));
            }
        };
    }
}
